import { Button, message, Checkbox } from "antd";
import { DownOutlined } from '@ant-design/icons';
import eventBus from "../../framework/common/eventBus";
import { useForm } from "../../framework/common/context/metadata-context";
import { useLayoutEffect, useState } from "react";
import clsx from "clsx";
import request from "../../framework/common/utils/request";
import { getQuery, isNoEmptyArray } from "../../framework/common/utils";
import { getApproveBtnName } from "../../RuntimeForm/ApproveStep/stepUtility";
import { useUpdate } from "ahooks";
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import jQuery from "jquery";
window.jQuery = jQuery;

export default function PrintBtn() {
  const { data: tplData } = useForm();
  const [exportPDFLoading, setExportPDFLoading] = useState(false);

  function handleResetForm() {
    eventBus.publish("group.resetForm");
    eventBus.publish("relation.update")
  }
  function handlePrint() {
    window.print();
  }
  function handleExportPDF() {
    setExportPDFLoading(true);
    if (tplData.printSetting && tplData.printSetting.printExportPdfType == "1") {
      console.log(tplData.hideInfo);
      //后端导出pdf
      request({
        url: "/flowinstance/approval/export-pdf-by-tools" + window.location.search + "&process_name=" + tplData.ProcessInfo.Title,
        method: "POST",
        data: tplData.hideInfo,
      })
        .then(function (result) {
          if (result.code == 1) {
            var url = result.data.url || "";
            window.location.href = url;
            setTimeout(() => {
              setExportPDFLoading(false);
            }, 5000);
          
          } else {
            setExportPDFLoading(false);
            message.error("导出失败");
          }
        })
        .catch(function () {
          debugger
          message.error("导出失败");
        });
    } else {
      frontendExportPdf({
        tplData: tplData,
        setExportPDFLoading: setExportPDFLoading
      });
    }
  }
  return (
    <div className=" print-header-button h-[50px] flex  items-center justify-center float-right">

      <ProcessTitleControl des="流程标题显示控制"/>
      <AuditRecordsControl des="审批记录信息显示控制" />

      <Button onClick={handleResetForm}>重置表单</Button>
      <div className="divider"></div>
      <Button className={clsx("mr-3", exportPDFLoading && "pl-6px-Btn")} onClick={handleExportPDF} loading={exportPDFLoading}>
        导出{exportPDFLoading ? "中" : "PDF"}
      </Button>
      <Button className="w-[80px]" type="primary" onClick={handlePrint}>
        打印
      </Button>
    </div>
  );
}

//审批流程显示隐藏控制
function AuditRecordsControl(){
  const { data: tplData } = useForm();
  const updater = useUpdate();
  if(isNoEmptyArray(tplData.ApproveSteps) === false){
    //不存在步骤信息时，不展示审批记录控制信息
    return null;
  }
  return <div className="inline-block mr-10px relative button-list-container">
    <Button className="button-select">
      <Checkbox
        checked={tplData.hideInfo.show_audit_records}
        onChange={(e)=>{
          //change更新打印隐藏配置信息，供后端打印传参使用
          tplData.hideInfo.show_audit_records = e.target.checked;
          if(e.target.checked === false){
            //如果关闭审批记录，同步更新 协商信息 和 交办信息 为隐藏
            tplData.hideInfo.show_consult_records = false;
            tplData.hideInfo.show_assigned_records = false;
          }
          eventBus.publish("updateApproveStepPrint.update");//更新流程图
          updater();
        }}
      >审批记录</Checkbox>
      <DownOutlined />
    </Button>
    <div className="absolute bg-white w-full button-list-wrap">
      <span className="pl-10px py-2 block">
        <Checkbox className="w-full"
          checked={tplData.hideInfo.show_consult_records}
          onChange={(e)=>{
            //change更新打印隐藏配置信息，供后端打印传参使用
            tplData.hideInfo.show_consult_records = e.target.checked;
            eventBus.publish("updateApproveStepPrint.update");//更新流程图
            updater();
          }}
        >
          {
            getApproveBtnName({approveType:"Consult", btnText:"协商", tplData: tplData})
          }
        </Checkbox>
      </span>
      <span className="pl-10px pb-2 block">
        <Checkbox className="w-full"
          checked={tplData.hideInfo.show_assigned_records}
          onChange={(e)=>{
            //change更新打印隐藏配置信息，供后端打印传参使用
            tplData.hideInfo.show_assigned_records = e.target.checked;
            eventBus.publish("updateApproveStepPrint.update");//更新流程图
            updater();
          }}
        >
          {
            getApproveBtnName({approveType:"Assigned", btnText:"交办", tplData: tplData})
          }
        </Checkbox>
      </span>
    </div>
  </div>
}

//流程标题控制按钮
function ProcessTitleControl(){
  const { data: tplData } = useForm();
  let updater = useUpdate();

  if(!tplData?.printSetting?.printProcessTitle){
    //未开启打印标题设置，直接返回null
    return null;
  }
  return <span className="mr-10px">
    <Button className="button-select">
    <Checkbox
      checked={tplData.hideInfo.show_process_title}
      onChange={(e)=>{
        //change更新打印隐藏配置信息，供后端打印传参使用
        tplData.hideInfo.show_process_title = e.target.checked;
        eventBus.publish("updatePrintProcessBaseInfo.update");//更新流程图
        updater();
      }}
    >流程标题</Checkbox>
  </Button>
  </span>
}

//前端导出pdf
function frontendExportPdf({
  tplData,
  setExportPDFLoading
}){

  var pdfWidth = 594;//传入jspdf需要的宽度，导出html需要的宽度是 792 * 0.75 = 594
  var pdfHeight = 840;
  
  //把表单html复制到导出pdf上，
  jQuery("#js-exportPDF").html("")
  jQuery("#js-exportPDF").append(jQuery(".runtime-form").html());
  
  html2canvas(document.querySelector("#js-exportPDF"), { 
    async: true,
    logging:false,
    allowTaint : false,
    useCORS: true,
    backgroundColor:null,
    ignoreElements:function(element){
        return !element;
    } }).then(function (canvas) {

        let canvasWidth = canvas.width;//生成的img宽度
        let canvasHeight = canvas.height;//生成的img高度
        let pageHeight = canvasWidth / pdfWidth  * pdfHeight;//每一页需要展示的像素高度 792 / 594 * 840 = 1120
        let imageHeightToPdfHeight = pdfWidth / canvasWidth * canvasHeight;
        let leftHeight = canvasHeight;
        let position = 0
        let pageData = canvas.toDataURL('image/jpeg', 1.0);

        /*测试代码，把生成的图片放到页面上看效果 */
        // let $img = jQuery("<img src='" + pageData + "'>");
        // if(!jQuery("#js-exportPDF-test").length){
        //   jQuery("#js-exportPDF").after("<div id='js-exportPDF-test'></div>")
        // }
        // jQuery("#js-exportPDF-test").html("");
        // jQuery("#js-exportPDF-test").append($img);

        let PDF = new jsPDF('', 'pt', [pdfWidth, pdfHeight]);
        if (leftHeight < pageHeight) {
            PDF.addImage(pageData, 'JPG', 0, position, pdfWidth, imageHeightToPdfHeight)
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPG', 0, position, pdfWidth, imageHeightToPdfHeight)
            leftHeight -= pageHeight
            position -= pdfHeight
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }

        PDF.save(tplData.ProcessInfo.Title + '.pdf');
        jQuery("#js-exportPDF").html("");
        setExportPDFLoading(false);
    })
}